// pages/outvisit/trip/clockIn.js
var api = require("../../../utils/api.js");
var util = require("../../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tripState: 0,//出行状态
    pickerValue: [0, 0, 0],//下拉框的值
    clockType: ["中途打卡", "结束行程"],//打卡类型
    clockMatter: ["加油", "用餐", "洗车", "修车"],//打卡事项
    tripType: ["公司汽车", "私家汽车", "公共交通"],//出行方式
    longitude: "",//地图当前经度
    latitude: "",//地图当前纬度
    clockInTime: "",//打卡时间
    departureAddress: "",//出发地点
    clockInAddress: "",//打卡地点
    mileagePhotoId: "",//里程照片id
    mileagePhotoUrl: "",//里程照片路径
    fileUrlList: [],//附件照片
    outList: [],//今日外访清单
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var tripState = options.tripState;
    that.setData({
      tripState: tripState
    });
    if (tripState != 0) {
      // 获取当前出行方式
      that.getTripType();
    }
    // 设置当前位置坐标
    that.setLocation();
    // 获取今日外访相关
    that.getVisitToday();
  },

  // 设置打卡时间
  setClockInTime:function(){
    var myDate = Date.parse(new Date());
    var checkInTime = util.formatTimeTT(myDate, "h:m");
    checkInTime = checkInTime;
    this.setData({
      clockInTime: checkInTime
    });
  },

  // 设置当前位置坐标
  setLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        const longitude = res.longitude;
        const latitude = res.latitude;
        if (longitude == 0 || latitude == 0) {
          wx.showToast({
            title: "获取当前坐标失败",
            icon: "none"
          });
          return;
        }
        that.setData({
          longitude: longitude,
          latitude: latitude
        }, () => {
          //获取当前位置名称
          that.getLocationName();
        });
      }, fail: function (err) {
        wx.showToast({
          title: "获取当前坐标失败",
          icon: "none"
        });
      }
    });
  },

  //获取当前位置名称
  getLocationName: function () {
    var that = this;
    //根据坐标获取位置名称
    api.getLocationName(that.data.longitude, that.data.latitude).then(res => {
      that.setData({
        clockInAddress: res
      });
    });
  },

  // 获取当前出行方式
  getTripType: function () {
    var that = this;
    // // 获取上一个页面
    // var pages = getCurrentPages();
    // var page = pages[pages.length - 2];
    // var pickerValue = that.data.pickerValue;
    // var clockInRecord = page.data.clockInRecord;
    // pickerValue[2] = parseInt(clockInRecord[clockInRecord.length - 1].goWay);
    // that.setData({
    //   pickerValue: pickerValue
    // });
    // 获取上一个页面
    var pages = getCurrentPages();
    var page = pages[pages.length - 2];
    var pickerValue = that.data.pickerValue;
    var clockInRecord = page.data.clockInRecord;
    pickerValue[2] = that.data.tripType.indexOf(clockInRecord[clockInRecord.length - 1].goWay);
    that.setData({
      pickerValue: pickerValue
    });
  },

  // 获取今日外访相关
  getVisitToday: function () {
    var that = this;
    api.getVisitToday().then(res => {
      var outList = res.data.outList;
      if (outList.length > 0) {
        that.setData({
          departureAddress: outList[0].departureAddress,
          outList: outList
        });
      }
    });
  },

  //上传里程照片
  upLoadMileage: function (e) {
    var that = this;
    that.upLoad(1);
  },

  //上传附件照片
  upLoadAccessory: function (e) {
    var that = this;
    that.upLoad(2);
  },

  //上传附件
  upLoad: function (type) {
    var that = this;
    var sourceType = ['album', 'camera'];
    if (type == 1) {
      sourceType = ['camera'];
    }
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地ID列表，tempFilePaths可以作为img标签的src属性显示图片
        var size = tempFilePaths.length;
        for (var i = 0; i < size; i++) {
          wx.showLoading({
            title: '正在上传',
          });
          const uploadTask = wx.uploadFile({
            url: getApp().data.servsers + "/v1/api/oaProgress/saveFile",
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              'username': wx.getStorageSync('name'),
              'businessType': "出行打卡",
            },
            header: {
              'token': wx.getStorageSync('token')
            },
            success: function (res) {
              var data = res.data;
              var result = JSON.parse(data);
              var fileUrlListResult = result.data;
              if (result.msg == "success") {
                wx.hideLoading();
                wx.showToast({
                  title: "上传成功",
                  icon: 'none',
                  duration: 1000
                });
                //回显图片
                if (type == 1) {
                  that.setData({
                    mileagePhotoId: fileUrlListResult.id,
                    mileagePhotoUrl: fileUrlListResult.url
                  });
                } else if (type == 2) {
                  var list = that.data.fileUrlList;
                  list.push(fileUrlListResult);
                  that.setData({
                    fileUrlList: list
                  });
                }
              } else {
                if (result.code == 300) {
                  wx.showToast({
                    title: result.msg,
                    icon: "none"
                  });
                  setTimeout(function () {
                    api.logout();// 退出登录
                  }, 1500);
                } else {
                  wx.showToast({
                    title: "上传失败",
                    icon: 'none',
                    duration: 1000
                  });
                }
              }
            }
          })
        }
      }
    });
  },

  //显示图片
  showImg: function (option) {
    var that = this;
    var fileUrlListResult = that.data.fileUrlList;
    var imgUrls=[];
    for (var index in fileUrlListResult) {
      imgUrls[index] = fileUrlListResult[index].url;
    }
    var url = option.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: imgUrls
    });
  },

  //删除附件
  delImg: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          var fileUrlList = that.data.fileUrlList;
          for (var i = 0; i < fileUrlList.length; i++) {
            var urlOld = fileUrlList[i].url;
            if (url == urlOld) {
              fileUrlList.splice(i, 1);
              break;
            }
          }
          //移除后重新赋值
          that.setData({
            fileUrlList: fileUrlList
          })
        }
        else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 打卡
  clockIn: function (e) {
    var that = this;
    var params = e.detail.value;
    if (that.data.tripState == 0) {
      params.clockType = 1;
    } else {
      params.clockType = parseInt(that.data.pickerValue[0]) + 2;
    }
    params.longitude = that.data.longitude;
    params.latitude = that.data.latitude;
    // 验证
    // 打卡地点验证
    if (!params.address) {
      wx.showToast({
        title: "未获取到当前打卡地点",
        icon: "none"
      });
      return;
    }
    // 里程相关验证
    if ((that.data.tripState == 0 || that.data.pickerValue[0] != 0 || (that.data.tripState == 1 && that.data.pickerValue[0] == 0 && that.data.pickerValue[1] == 0)) && that.data.pickerValue[2] != 2) {
      if (!params.enduranceMile) {
        wx.showToast({
          title: "请输入续航里程",
          icon: "none"
        });
        return;
      } else if (!/^\d+(\.\d+)?$/.exec(params.enduranceMile)) {
        wx.showToast({
          title: "请输入正确的续航里程",
          icon: "none"
        });
        return;
      }
    }
    if ((that.data.tripState == 0 || that.data.pickerValue[0] != 0) && that.data.pickerValue[2] != 2) {
      if (!params.startMileage) {
        wx.showToast({
          title: "请输入里程",
          icon: "none"
        });
        return;
      } else if (!/^\d+(\.\d+)?$/.exec(params.startMileage)) {
        wx.showToast({
          title: "请输入正确的里程",
          icon: "none"
        });
        return;
      }
      if (!that.data.mileagePhotoId){
        wx.showToast({
          title: "请拍摄汽车里程照片",
          icon: "none"
        });
        return;
      }
      params.pictureUrl = that.data.mileagePhotoId;
    }
    // 附件验证
    if (that.data.tripState != 0 && that.data.pickerValue[0] == 0) {
      var fileUrlList = that.data.fileUrlList;
      if (fileUrlList.length == 0) {
        wx.showToast({
          title: "请上传附件",
          icon: "none"
        });
        return;
      }
      var listFile = [];
      for (var i = 0; i < fileUrlList.length; i++) {
        listFile.push(fileUrlList[i].id);
      }
      params.listFile = listFile;
    }
    // 将下拉框的值转换成文字
    if (params.clockMatter != undefined) {
      params.clockMatter = that.data.clockMatter[params.clockMatter];
    }
    if (params.goway != undefined) {
      params.goway = that.data.tripType[params.goway];
    }
    api.clockIn(params);
  },

  //下拉框选择事件
  bindPickerChange: function (e) {
    let pickerValue = this.data.pickerValue;
    pickerValue[parseInt(e.currentTarget.dataset.id)] = e.detail.value;
    this.setData({
      pickerValue: pickerValue
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 设置打卡时间
    this.setClockInTime();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
